package com.youlu.campus.web.order.service;

import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.order.entity.vo.AddressVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.youlu.campus.web.order.entity.UserAddressPO;

import java.util.Date;
import java.util.List;

/**
 * @author zgz
 * @date 2020/8/3 18:28
 */

@Service
@Slf4j
public class AddressService extends BaseService {

    public boolean deleteUserAddress(String userId, String id) {
        log.info("deleteUserAddress userId {}", userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("id").is(id));
        mongoTemplate.remove(query, UserAddressPO.class);
        return true;
    }

    public List<UserAddressPO> getUserAddress(String userId) {
        log.info("getUserAddress userId {}", userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        List<UserAddressPO> addressPO = mongoTemplate.find(query, UserAddressPO.class);
        if (addressPO == null) {
            return null;
        }
        return addressPO;
    }

    public String addAddress(AddressVO addressVO) {
        String userId = RequestContext.getUserId();
        log.info("addAddress userId {} addressVO {}", userId, addressVO);
        if (StringUtils.isBlank(addressVO.getAddressId())) {
            addressVO.setAddressId(null);
        }
        UserAddressPO addressPO = new UserAddressPO();
        addressPO.setUserId(userId);
        BeanUtils.copyProperties(addressVO, addressPO);
        addressPO.setId(addressVO.getAddressId());
        if (StringUtils.isBlank(addressVO.getAddressId())) {
            addressPO.setCreatedTime(new Date());
        }
        addressPO.setUpdatedTime(new Date());
        mongoTemplate.save(addressPO);
        return addressPO.getId();
    }


}
